/**
 * 项目数据结构测试脚本
 * 验证 projects/ 目录下的文件结构是否正确
 */

const fs = require('fs').promises;
const path = require('path');

const PROJECTS_DIR = path.join(__dirname, '../projects');
const PROJECTS_INDEX = path.join(PROJECTS_DIR, 'projects.json');

async function testProjectStructure() {
    console.log('╔════════════════════════════════════════╗');
    console.log('║   📂 项目数据结构测试                  ║');
    console.log('╚════════════════════════════════════════╝\n');

    try {
        // 1. 检查 projects 目录
        console.log('1️⃣ 检查 projects/ 目录...');
        try {
            await fs.access(PROJECTS_DIR);
            console.log('   ✅ projects/ 目录存在');
        } catch {
            console.log('   ❌ projects/ 目录不存在');
            return;
        }

        // 2. 检查 projects.json
        console.log('\n2️⃣ 检查 projects.json...');
        let index;
        try {
            const data = await fs.readFile(PROJECTS_INDEX, 'utf-8');
            index = JSON.parse(data);
            console.log('   ✅ projects.json 存在且格式正确');
            console.log(`   📊 项目总数: ${index.projects.length}`);
            console.log(`   🎯 默认项目: ${index.defaultProject}`);
        } catch (error) {
            console.log('   ❌ projects.json 读取失败:', error.message);
            return;
        }

        // 3. 验证每个项目的文件结构
        console.log('\n3️⃣ 验证项目文件结构...\n');
        
        for (const project of index.projects) {
            console.log(`   📁 ${project.name} (${project.id})`);
            
            // 检查项目目录
            const projectDir = path.join(PROJECTS_DIR, project.path);
            try {
                await fs.access(projectDir);
                console.log(`      ✅ 文件夹存在: ${project.path}/`);
            } catch {
                console.log(`      ❌ 文件夹不存在: ${project.path}/`);
                continue;
            }

            // 检查 project.json
            const configFile = path.join(projectDir, 'project.json');
            try {
                const configData = await fs.readFile(configFile, 'utf-8');
                const config = JSON.parse(configData);
                console.log(`      ✅ project.json 存在且格式正确`);
                console.log(`         - 名称: ${config.name}`);
                console.log(`         - 场景数: ${config.scenes?.length || 0}`);
                console.log(`         - 默认场景: ${config.defaultScene}`);
                
                // 验证数据一致性
                if (config.name !== project.name) {
                    console.log(`      ⚠️ 警告: project.json 中的名称与索引不一致`);
                    console.log(`         索引: ${project.name}`);
                    console.log(`         配置: ${config.name}`);
                }
            } catch (error) {
                console.log(`      ❌ project.json 读取失败:`, error.message);
            }

            // 检查 README.md
            const readmeFile = path.join(projectDir, 'README.md');
            try {
                await fs.access(readmeFile);
                console.log(`      ✅ README.md 存在`);
            } catch {
                console.log(`      ⚠️ README.md 不存在（可选）`);
            }

            console.log('');
        }

        // 4. 检查是否有未索引的项目文件夹
        console.log('4️⃣ 检查未索引的项目...\n');
        const dirs = await fs.readdir(PROJECTS_DIR, { withFileTypes: true });
        const projectDirs = dirs.filter(d => d.isDirectory()).map(d => d.name);
        const indexedPaths = index.projects.map(p => p.path);
        
        const unindexed = projectDirs.filter(dir => !indexedPaths.includes(dir));
        
        if (unindexed.length > 0) {
            console.log('   ⚠️ 发现未索引的项目文件夹:');
            unindexed.forEach(dir => {
                console.log(`      - ${dir}`);
            });
            console.log('\n   💡 提示: 可能需要在 projects.json 中添加这些项目');
        } else {
            console.log('   ✅ 所有项目文件夹都已正确索引');
        }

        // 5. 显示目录树
        console.log('\n5️⃣ 项目目录结构:\n');
        console.log('projects/');
        console.log('├── projects.json');
        for (let i = 0; i < index.projects.length; i++) {
            const project = index.projects[i];
            const isLast = i === index.projects.length - 1;
            const prefix = isLast ? '└──' : '├──';
            const indent = isLast ? '    ' : '│   ';
            
            console.log(`${prefix} ${project.path}/`);
            
            // 显示项目文件
            const projectDir = path.join(PROJECTS_DIR, project.path);
            try {
                const files = await fs.readdir(projectDir);
                files.forEach((file, j) => {
                    const filePrefix = j === files.length - 1 ? '└──' : '├──';
                    console.log(`${indent}${filePrefix} ${file}`);
                });
            } catch {
                console.log(`${indent}└── (无法读取)`);
            }
        }

        console.log('\n╔════════════════════════════════════════╗');
        console.log('║   ✅ 测试完成                          ║');
        console.log('╚════════════════════════════════════════╝');

    } catch (error) {
        console.error('\n❌ 测试过程中出错:', error);
    }
}

// 运行测试
testProjectStructure();

